package org.cxa.rpc.cloud.configurationConsole.userManagement;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import java.awt.BorderLayout;

import javax.swing.JTable;

import org.cxa.rpc.cloud.client.TransientDevice;
import org.cxa.rpc.cloud.server.components.authentication.Group;
import org.cxa.rpc.cloud.server.components.authentication.User;
import org.cxa.rpc.messages.ResponseRpcMessage;

import javax.swing.JToolBar;
import javax.swing.JButton;

import java.awt.Component;

import javax.swing.Box;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JTabbedPane;

public class UserManagementPanel extends JPanel
{	
	private static final long serialVersionUID = 7665962183319223315L;
	private static final String TAB_TITLE_USERS = "Users";
	private static final String TAB_TITLE_GROUPS = "Groups";
	
	
	private final JTable tblUsers;
	private final JTable tblGroups;
	private final JTabbedPane tabbedPane;
	private final TransientDevice tDev;

	
	/**
	 * Create the panel.
	 */
	public UserManagementPanel(TransientDevice tDevIn)
	{
		this.tDev = tDevIn;
		
		setLayout(new BorderLayout(0, 0));
		
		tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
		add(tabbedPane, BorderLayout.CENTER);
		
		JScrollPane scrollUsers = new JScrollPane();
		tabbedPane.addTab(TAB_TITLE_USERS, null, scrollUsers, null);
		
		tblUsers = new JTable();
		tblUsers.setModel(new UserTableModel(tDevIn));
		scrollUsers.setViewportView(tblUsers);
		
		JScrollPane scrollGroups = new JScrollPane();
		tabbedPane.addTab(TAB_TITLE_GROUPS, null, scrollGroups, null);
		
		tblGroups = new JTable();
		tblGroups.setModel(new GroupTableModel(tDevIn));
		scrollGroups.setViewportView(tblGroups);
		
		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		add(toolBar, BorderLayout.SOUTH);
		
		JButton btnAdd = new JButton("Add");
		btnAdd.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				String selectedTitle = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
				if( selectedTitle.equals(TAB_TITLE_USERS) )
				{
					AddUserDialog aud = new AddUserDialog(tDev);
					aud.setLocationRelativeTo(UserManagementPanel.this.getTopLevelAncestor());
					aud.setVisible(true);
				}
				else if( selectedTitle.equalsIgnoreCase(TAB_TITLE_GROUPS) )
				{
					String newGroupName = JOptionPane.showInputDialog(null, "Enter the group name:", "Add new group", JOptionPane.PLAIN_MESSAGE);
					if( newGroupName != null )
					{
						Group groupToAdd = new Group(newGroupName);
						Map<String, Object> params = new HashMap<String, Object>();
						params.put("group", groupToAdd);
						
						ResponseRpcMessage resp = tDev.sendRequest("/sys/auth", "addGroup", params);
						if( !resp.getWasSuccessful() )
						{
							JOptionPane.showMessageDialog(null, String.format("Error adding group:\n%s", resp.getException().getFormattedErrorString())); 
						}
						else
						{
							JOptionPane.showMessageDialog(null, 
									String.format("Added group: '%s'", newGroupName), 
									"Added Group", JOptionPane.INFORMATION_MESSAGE);
						}
					}
				}
			}
		});
		toolBar.add(btnAdd);
		
		JButton btnRemove = new JButton("Remove");
		btnRemove.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				String selectedTitle = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
				if( selectedTitle.equals(TAB_TITLE_USERS) )
				{
					User selectedUser = ((UserTableModel)tblUsers.getModel()).getUserAtRow(tblUsers.getSelectedRow());
					if( selectedUser == null ) return;
					
					int userSel = JOptionPane.showConfirmDialog(null, String.format("Are you sure you want to delete '%s'", selectedUser.getEmail()), "Confirm deletion", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
					if( userSel == JOptionPane.YES_OPTION ) ((UserTableModel)tblUsers.getModel()).deleteUserByEmail(selectedUser.getEmail());
				}
				else if( selectedTitle.equalsIgnoreCase(TAB_TITLE_GROUPS) )
				{
					Group selectedGroup = ((GroupTableModel)tblGroups.getModel()).getGroupAtRow(tblGroups.getSelectedRow());
					if( selectedGroup == null ) return;
					
					int groupSel = JOptionPane.showConfirmDialog(null, String.format("Are you sure you want to delete '%d::%s'", selectedGroup.getId(), selectedGroup.getName()), "Confirm deletion", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
					if( groupSel == JOptionPane.YES_OPTION ) ((GroupTableModel)tblGroups.getModel()).deleteGroupById(selectedGroup.getId());
				}
			}
		});
		toolBar.add(btnRemove);
		
		Component horizontalGlue = Box.createHorizontalGlue();
		toolBar.add(horizontalGlue);
		
		JButton btnRefresh = new JButton("Refresh");
		btnRefresh.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				if( tabbedPane.getSelectedIndex() == 0 ) ((UserTableModel)tblUsers.getModel()).refreshFromServer();
				else ((GroupTableModel)tblGroups.getModel()).refreshFromServer();
			}
		});
		toolBar.add(btnRefresh);

	}
}
